package home.my.base.util;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

public class MyDataSource extends org.springframework.jdbc.datasource.DriverManagerDataSource {

	private static final String CLASS_ROOT_STRING = "CLASS_ROOT";
	private static final String CONN_URL_STRING_PREFIX = "jdbc:sqlite:";
	private static Logger logger = Logger.getLogger(MyDataSource.class);
	
	@Override
	public void setUrl(String url) {
		File dbFile = null;
		if(url.contains(CLASS_ROOT_STRING)){
			logger.debug("使用相对路径，开始处理数据库连接串。");
			String[] subs = url.split(CLASS_ROOT_STRING);
			if( !(subs[1].startsWith("/") || subs[1].startsWith("\\")) ){
				subs[1] = "/" + subs[1];
			}
			dbFile = new File(this.getClass().getResource("/").getFile() + subs[1]);
			try {
				url = subs[0] + dbFile.getCanonicalPath();
			} catch (IOException e) {
				throw new RuntimeException("使用相对路径方式，获取文件绝对路径报错：",e);
			}
		}else{
			String fileName = url.substring(CONN_URL_STRING_PREFIX.length(),url.length());
			dbFile = new File(fileName);
		}
		if(!dbFile.exists()){
			throw new RuntimeException("数据库文件不存在:"+url);
		}
		logger.warn("数据库连接串为：" + url);
		super.setUrl(url);
	}

}